<?php
	/**
	 * TODO 基础分页的相同代码封装，使前台的代码更少
	 * @param $count 要分页的总记录数
	 * @param int $pagesize 每页查询条数
	 * @param array $filter 过滤条件
	 * @return \Think\Page
	 */
	function getpage($count, $pagesize = 10,$filter = '') {
		$p = new Think\Page($count,$pagesize,$filter);
		$p->setConfig('header', '<li><a href="#">共%TOTAL_PAGE%页</a></li><li><a href="#">('.$count.'条记录)</a></li>');
		$p->setConfig('prev', '上一页');
		$p->setConfig('next', '下一页');
		$p->setConfig('last', '末页');
		$p->setConfig('first', '首页');
		$p->setConfig('theme', '<ul class="pagination" style="float:right"><li>%FIRST%</li><li>%UP_PAGE%</li><li>%LINK_PAGE%</li><li>%DOWN_PAGE%</li><li>%END%</li><li>%HEADER%</li></ul>');
		$p->lastSuffix = false;//最后一页不显示为总页数
		return $p;
	}
	
	/*
	* curl get传送参数
	*/
	function curl_get($url){
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		$output = curl_exec($ch); 
		curl_close($ch);
		return $output;
	}
	
	/*
	* curl post传送参数
	*/
	function curl_post($url,$param){
		// \Think\Log::write($url.serialize($param),'WARN');
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_TIMEOUT,10);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$param);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	
	/*
	* curl post传送参数
	*/
	function sync_curl_post($url,$param){
		// \Think\Log::write($url.serialize($param),'WARN');
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_TIMEOUT,10);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$param);
		curl_setopt($ch,CURLOPT_HTTPHEADER,array(
            'Content-Type:text/json;charset=utf-8',
            'Content-Length:'.strlen($param)
        ));
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}

	/**
	* FunName:verificationData
	* Description:数据校验
	* @param:$data string 校验的数据
	* @param:$type string 需要校验数据的类型 float:浮点校验 integer：整数校验
	* @param:$flag string 数据校验类型的各种分类 -10（负+0）、-1（负）、10（正+0）、1（正）
	*/
	function verificationData($data,$type,$flag=''){
		if($preg = pregRule($type,$flag)){
			if(preg_match($preg,trim($data))){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}
	
	/*
	* FunName:pregRule
	* Description:正则规则
	* @param:$data string 校验的数据
	* @param:$type string 需要校验数据的类型 float:浮点校验 integer：整数校验
	* @param:$flag string 数据校验类型的各种分类 -10（负+0）、-1（负）、10（正+0）、1（正）
	*/
	function pregRule($type,$flag=''){
		$preg = '';
		if($type=='float'){//浮点校验
			switch($flag){
				case '-10': //负浮点数+0
					$preg = '/^((-\d+(\.\d+)?)|(0+(\.0+)?))$/';
					break;
				case '-1': //负浮点数
					$preg = "/^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/";
					break;
				case '10': //正浮点数+0
					$preg = "/^\d+(\.\d+)?$/";
					break;
				case '1': //正浮点数
					$preg = "/^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/";
					break;
				default:
					$preg = '/^(-?\d+)(\.\d+)?/';
					break;
			}
		}else if($type=='integer'){
			switch($flag){
				case '-10': //负整数 + 0
					$preg = '/^((-\d+)|(0+))$/';
					break;
				case '-1': //负整数
					$preg = "/^\-[1-9][0-9]*$/";
					break;
				case '10': //正整数+0
					$preg = "/^\d+$/";
					break;
				case '1': //正整数
					$preg = "/^\+?[1-9][0-9]*$/";
					break;
				default:
					$preg = '/^-?\d+$/';
					break;
			}
		}else if($type=='checkname'){ //验证中文名字
			$preg = '/^[\x{4e00}-\x{9fa5}]+$/u';
		}else if($type=='checkmobile'){ //验证手机号
			$preg = '/^0?(13|14|15|17|18)[0-9]{9}$/';
		}else if($type=='checkInums'){ //
			$preg = '/^\d+(\.{0,1}\d+){0,1}$/';
		}else if($type=='checkemail'){//验证邮箱
			$preg = '/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i';
		}else if($type=='checkprice'){ //验证金额价格
			$preg = '/(?!^0*(\.0{1,2})?$)^\d{1,13}(\.\d{1,3})?$/';
		}
		return $preg;
	}
	
	/*
	* FunName:isIdCard
	* Description:身份证检测
	* @param:$cardid string 身份证号
	*/
	function isIdCard($cardid){
		$preg='/^[1-9]\d{5}(19\d{2}|[2-9]\d{3})((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])(\d{4}|\d{3}X)$/i'; //身份证正则表达式(18位)
		$stard = "10X98765432"; //最后一位身份证的号码
		$first=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2); //1-17系数
		$sum=0;
		if(!preg_match($preg,$cardid)){
			return false;
		}
		$birthday=substr($cardid,6,8);
		if(!isDate($birthday,'Ymd')){ //验证生日是否合法
			return false;
		}
		for($i = 0;$i<strlen($cardid)-1;$i++){ //累加前17位数字和对应系数乘积
			$sum += $cardid[$i]*$first[$i];
		}
		$result = $sum%11; //除11取余
		$last = $stard[$result]; //获取对应最后一位的值
		if(strtoupper($cardid[strlen($cardid)-1])==$last){
			return true;
		}else{
			return false;
		}
	}
	
	function isDate($date,$format) {
		$unixTime = strtotime($date);
		if(!$unixTime) { //strtotime转换不对，日期格式显然不对。
			return false;
		}
		//校验日期的有效性，只要满足其中一个格式就OK	
		if(date($format,$unixTime)==$date){
			return true;
		}else{
			return false;
		}
    }
	
	/*
	* FunName: returnFilter
	* Description:返回搜索过滤条件
	* @param:$filter array 搜索条件数组
	*/
	function returnFilter($filter = ''){
		if(is_array($filter)&&count($filter)>0){
			foreach($filter as $key=>$val){
				$filter[$key] = str_replace("+"," ",urldecode($val));
			}
		}
		return $filter;
	}
	
	/*
	* FunName: splitRegion
	* Description:分割区域转为省市区地址
	* @param:$region string 地址区域
	*/
	function splitRegion($region = ''){
		$area = array();
		$area = explode("-",$region);
		$province = $area[0];
		$province = mb_substr($province,0,2,'utf-8');
		if($province == '内蒙'){
			$province = '内蒙古';
		}elseif($province == '黑龙'){
			$province = '黑龙江';
		}
		return array($province,$area[1],$area[2]);
	}
	
	/*
	* FunName: xmltoarray
	* Description:xml转化为数组
	* @param:$xml xml xml数据
	*/
	function xmltoarray($xml){
		// $p = xml_parser_create();
            // xml_parse_into_struct($p, $xml, $vals, $index);
            // xml_parser_free($p);
            // $data = "";
            // foreach ($index as $key=>$value) {
                // if($key == 'xml' || $key == 'XML') continue;
                // $tag = $vals[$value[0]]['tag'];
                // $value = $vals[$value[0]]['value'];
                // $data[$tag] = $value;
            // }
            // return $data;
		// if(!$xml){
            // return false;
        // }
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
	}
	
	//字符串截取
	function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
		if(function_exists("mb_substr")){
			if($suffix){
				return mb_substr($str, $start, $length, $charset)."...";
			}else{
				return mb_substr($str, $start, $length, $charset);
			}
		}elseif(function_exists('iconv_substr')) {
			if($suffix){
				return iconv_substr($str,$start,$length,$charset)."...";
			}else{
				return iconv_substr($str,$start,$length,$charset);
			}
		}
		$re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("",array_slice($match[0], $start, $length));
		if($suffix){
			return $slice."...";
		}else{
			return $slice;
		}
	}
	
	/*
	* FunName: getExcel
	* Description:获取excel导出
	* @param:$fileName string 导出表的名字
	* @param:$headArr string 导出表的第一行名称
	* @param:$data string 导出表的数据(array)
	*/
	function getExcel($fileName,$headArr,$data){
		//header("Content-type: text/html;charset=utf-8");
		//对数据进行检验
		if(empty($data) || !is_array($data)){
		   die("data must be a array");
		}
		//检查文件名
		if(empty($fileName)){
		   exit;
		}
		$date = date("Y_m_d",time());
		$fileName .= "_{$date}.xls";
		import("Org.Util.PHPExcel");
		import("Org.Util.PHPExcel.Writer.Excel5");
		import("Org.Util.PHPExcel.IOFactory.php");
		//创建PHPExcel对象，注意，不能少了\
		$objPHPExcel = new \PHPExcel();
		$objProps = $objPHPExcel->getProperties();
				 
		//设置表头
		$key = ord("A");
		$key2 = ord("@");
		foreach($headArr as $v){
			if($key>ord("Z")){
				$key2 += 1;
				$key = ord("A");
				$colum = chr($key2).chr($key);
			}else{
				if($key2>=ord("A")){  
					$colum = chr($key2).chr($key);  
				}else{  
					$colum = chr($key);  
				}
			}
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1',$v);
			$key += 1;
		}	 
		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();
		foreach($data as $key => $rows){ //行写入
			$span = ord("A");
			$span2 = ord("@");
			foreach($rows as $keyName=>$value){// 列写入
				//$value=iconv("utf-8","gb2312",$value);
				if($span>ord("Z")){
					$span2 += 1;
					$span = ord("A");
					$j = chr($span2).chr($span);
				}else{
					if($span2>=ord("A")){
						$j = chr($span2).chr($span);
					}else{
						$j = chr($span);
					}
				}
				$objActSheet->setCellValueExplicit($j.$column,$value,PHPExcel_Cell_DataType::TYPE_STRING);
				$span++;
			}
			$column++;
		}
		ob_end_clean();//清除缓冲区,避免乱码
		$fileName = iconv("utf-8","gb2312",$fileName);
		//重命名表
		// $objPHPExcel->getActiveSheet()->setTitle('test');
		//设置活动单指数到第一个表,所以Excel打开这是第一个表
		$objPHPExcel->setActiveSheetIndex(0);
		header("Content-type: text/csv");//重要
		header("Content-Type: application/force-download");
		//header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=\"$fileName\"");
		//header('Cache-Control: max-age=0');
		header('Cache-Control: must-revalidate, post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); //文件通过浏览器下载
		exit;
	}
	
	/*
	* FunName:importExcel
	* Description:excel导入
	* @param:$fileName string 导出表的名字
	* @param:$exts string 导入文件后缀
	*/
    function importExcel($filename, $exts='xls'){
        //导入PHPExcel类库,因为PHPExcel没有用命名空间,只能import导入
        import("Org.Util.PHPExcel");
        //创建PHPExcel对象,注意,不能少了
        $PHPExcel = new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }else if($exts == 'xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        }
        //载入文件
        $PHPExcel = $PHPReader->load($filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet = $PHPExcel->getSheet(0);
        //获取总列数
        $allColumn = $currentSheet->getHighestColumn();
        //获取总行数
        $allRow = $currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=2;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $data[$currentRow][$currentColumn]=(string)$currentSheet->getCell($address)->getValue();
            }
        }
		return $data;
    }
	
	/**
     *  判断字符串是否在数组中，包括二维数组--这里只能判断二维数组
     * @param $str
     * @param $arr
     * @return bool
     */
    function array_multi_search($str,$arr){
        if(in_array($str,$arr)){
            return true;
        }
        foreach ($arr as $row){
            if(array_multi_search($str,$row)){
                return true;
            }
        }
        return false;
    }

	/**
     * Emoji原形转换为String
     * @param string $content
     * @return string
     */
    function emojiEncode($content){
        return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($str) {
            return addslashes($str[0]);
        }, json_encode($content)));
    }

    /**
     * Emoji字符串转换为原形
     * @param string $content
     * @return string
     */
    function emojiDecode($content){
        return json_decode(preg_replace_callback('/\\\\\\\\/i', function () {
            return '\\';
        }, json_encode($content)));
    }

    /**
     * Emoji字符串清清理
     * @param string $content
     * @return string
     */
    function emojiClear($content){
        return preg_replace_callback('/./u', function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        }, $content);
    }

	/*
	* FunName: wxQrcodeHttpPsot
	* Description:获取微信qrcode post方法
	*/
	function wxQrcodeHttpPsot($url,$data){
		$ch = curl_init();
		/* 设置验证方式 */
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8',
			'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
		/* 设置返回结果为流 */
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		/* 设置超时时间*/
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		/* 设置通信方式 */
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$result = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if($result === false){
			$this->errorMsg = 'Curl error: '.$error;
			return false;
		}else{
			return $result;
		}
	}
	
	/*
	* FunName: wxNonceStr
	* Description:生成随机数算法
	*/
	function wxNonceStr(){
		$result = '';
		$str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
		for($i=0;$i<32;$i++){
			$result .= $str[rand(0,48)];
		}
		return $result;
	}
	
	/*
	* FunName: wxSign
	* Description:微信支付sign值生成
	* @param:$data array 参数
	*/
	function wxSign($data = ''){
		if(is_array($data)&&count($data)>0){
			$data = array_filter($data);
			ksort($data);
			$str = http_build_query($data).'&key='.C('key');
			$str = urldecode($str);
			return strtoupper(md5($str));
		}else{
			return false;
		}
	}

	/**
	* FunName: arraytoxml
	* Description:将数组转换成xml格式（简单方法）
	* @param [type] $data [数组]
	* @return [type]  [array 转 xml]
	*/
	function arraytoxml($data){
		$str='<xml>';
		foreach($data as $k=>$v) {
			$str.='<'.$k.'>'.$v.'</'.$k.'>';
		}
		$str.='</xml>';
		return $str;
	}
	
	/*替换字符串中间为星号*/
	function substr_cut($user_name){
        $strlen = mb_strlen($user_name, 'utf-8');
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr  = mb_substr($user_name, -1, 1, 'utf-8');
        return $strlen == 2 ? $firstStr . substr(str_repeat('*', mb_strlen($user_name, 'utf-8') - 1),0,3) : $firstStr . substr(str_repeat("*", $strlen - 2),0,3) . $lastStr;
    }
	
	/**
	* [curl_post_ssl 发送curl_post数据]
	* @param [type] $url  [发送地址]
	* @param [type] $xmldata [发送文件格式]
	* @param [type] $second [设置执行最长秒数]
	* @param [type] $aHeader [设置头部]
	* @return [type]   [description]
	*/
	function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
		$isdir = $_SERVER['DOCUMENT_ROOT']."/Cert/";//证书位置;绝对路径
		$ch = curl_init();//初始化curl
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
		curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
		curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
		curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
		curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
// 		curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
// 		curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
		if(count($aHeader) >= 1){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
		}
		curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);//全部数据使用HTTP协议中的"POST"操作来发送
		$data = curl_exec($ch);//执行回话
		if($data){
			curl_close($ch);
			return $data;
		}else{
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n";
			curl_close($ch);
			return false;
		}
	}
	
	function guanyi_curl($url, $data) {
        $data_string = json_encode_ch($data);
        $data_string = urlencode($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        /* 设置超时时间*/
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type:text/json;charset=utf-8',
            'Content-Length:'.strlen($data_string)
        ));
        $data = curl_exec($ch);//执行回话
		if($data){
			curl_close($ch);
			return $data;
		}else{
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n";
			curl_close($ch);
			return false;
		}
    }
    
    function json_encode_ch($arr) {
        return urldecode(json_encode(url_encode_arr($arr)));
    }
    
    function url_encode_arr($arr) {
        if(is_array($arr)){
            foreach ($arr as $k => $v){
                $arr[$k] = url_encode_arr($v);
            }
        }elseif(!is_numeric($arr) && !is_bool($arr)){
            $arr = urlencode($arr);
        }
        return $arr;
    }
    
    /**
    * 获取解析地址-腾讯地址api
    */
    function analysisTxAddress($address = ''){
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/?address='.$address.'&key='.C('tx_addr_key');
        return curl_get($url);
    }
    
    /**
    * 获取自定义的header数据
    */
    function get_all_headers(){
        // 忽略获取的header数据
        $ignore = array('host','accept','content-length','content-type');
        $headers = array();
        foreach($_SERVER as $key=>$value){
            if(substr($key, 0, 5)==='HTTP_'){
                $key = substr($key, 5);
                $key = str_replace('_', ' ', $key);
                $key = str_replace(' ', '-', $key);
                $key = strtolower($key);
                if(!in_array($key, $ignore)){
                $headers[$key] = $value;
                }
            }
        }
        return $headers;
    }
?>